﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LevenBlog.Core.Data;
using LevenBlog.Core.Entities;
using LevenBlog.Core.Cache;

namespace LevenBlog.Core.Service {
    public static class Archive {
        private static readonly string cacheName="levenblog_servicecache_archive";

        public static IList<lb_archive> Get(IDbProvider provider) {
            IList<lb_archive> find = ObjectCache.Get<IList<lb_archive>>(cacheName);
            if (find == null) {
                find = ProviderManager.Factory.Archive.Get(provider) as List<lb_archive>;
                ObjectCache.Insert(cacheName, find);
            }
            return find;
        }

        public static lb_archive Get(IDbProvider provider, int id) {
            //return ProviderManager.Factory.Archive.Get(provider, id);
            return Get(provider).FirstOrDefault(a => a.id == id);
        }

        public static void InserOneBlog(IDbProvider provider, int year, int month) {
            lb_archive archive = null;
            try {
                //archive = archiveList.Single(ar => ar.year == year && ar.month == month);
                archive = Get(provider).FirstOrDefault(a => a.year == year && a.month == month);
                archive.num++;
                ProviderManager.Factory.Archive.Update(provider, archive);
            } catch {
                archive = new lb_archive();
                archive.year = year;
                archive.month = month;
                archive.num = 1;
                ProviderManager.Factory.Archive.Insert(provider, archive);
            }
            Remove();
        }

        public static void DeleteOneBlog(IDbProvider provider, int year, int month) {
            lb_archive archive = null;
            try {
                //archive = archiveList.Single(ar => ar.year == year && ar.month == month);
                archive = Get(provider).FirstOrDefault(a => a.year == year && a.month == month);
                archive.num--;
                if (archive.num > 0)
                    ProviderManager.Factory.Archive.Update(provider, archive);
                else
                    ProviderManager.Factory.Archive.Delete(provider, archive.id);
            } catch {
                throw new Exception("该月无存档日志.");
            }
            Remove();
        }

        public static void Remove() {
            ObjectCache.Remove(cacheName);
        }
    }
}
